package me.shurufa.fragments;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.text.SimpleDateFormat;

import me.shurufa.R;
import me.shurufa.model.LoginResponse;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Settings;

/**
 * 与登录相关基类
 *
 * @FileName: me.shurufa.fragments.AuthenticatorFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-15 09:49
 */
public class AuthenticatorFragment extends BaseFragment implements WeiboAuthListener, IUiListener {
    public static final int EXISTED_USER_ERROR = 2005;

    private static final String TAG = AuthenticatorFragment.class.getName();

    protected static final int VALUE_APP = 1;

    protected static final int VALUE_SINA = 2;

    protected static final int VALUE_QQ = 3;

    protected static final int VALUE_WECHAT = 4;

    protected static final String KEY_TOKEN = "token";

    protected static final String KEY_OPEN_ID = "openid";

    protected static final String KEY_USERNAME = "username";

    protected static final String KEY_PASSWORD = "password";

    protected static final String KEY_EMAIL = "email";

    protected static final int REQUEST_CODE_BIND_OR_REGISTER = 1;

    protected static final int REQUEST_CODE_COMPLETE_INFO = 2;

    protected AuthInfo mWeiboAuth;

    protected Oauth2AccessToken accessToken;

    protected SsoHandler mSsoHandler;

    protected Tencent mTencent;

    private String errorMsg;

    BroadcastReceiver mReciver = new BroadcastReceiver() {
        @Override
        public void onReceive (Context context, Intent intent){
            if (intent.getBooleanExtra("result", false)) {
                String code = intent.getStringExtra("code");
                afterLogin(VALUE_WECHAT, code, code);
            } else {
                Toast.makeText(getActivity(), getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTencent();
        initWeibo();
        initWechat();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity());
        lbm.unregisterReceiver(mReciver);
    }

    protected void initTencent() {
        try {
            mTencent = Tencent.createInstance(Constants.TencentAppId, Global.getContext());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    protected void initWeibo() {
        mWeiboAuth = new AuthInfo(getActivity(), Constants.SinaAppKey, Constants.SinaAppRedirectURI,
                Constants.SinaScope);
        mSsoHandler = new SsoHandler(getActivity(), mWeiboAuth);
    }

    protected void initWechat() {
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity());
        lbm.registerReceiver(mReciver, new IntentFilter(Constants.ACTION_WECHAT_LOGIN));
    }

    @Override
    public void onComplete(Object o) {
        JSONObject object = (JSONObject) o;
        try {
            LogUtils.d(TAG, "onTencentComplete, object is " + object.toString());
            String token = object.optString("access_token");
            String openId = object.optString("openid");
            String expireTime = object.optString("expires_in");
            Oauth2AccessToken qqAccessToken = new Oauth2AccessToken(token, expireTime);
            if (qqAccessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date
                        (qqAccessToken
                                .getExpiresTime()));
                LogUtils.d(TAG, "QQ log in, expire date is " + date);
            }
            afterLogin(VALUE_QQ, openId, token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(UiError uiError) {
        LogUtils.d(TAG,
                "onError, uiError is " + uiError.errorDetail + ", " + uiError.errorMessage);
        Toast.makeText(getActivity(),
                TextUtils.isEmpty(uiError.errorMessage) ? getString(R.string.qq_log_in_failed)
                        : uiError.errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onComplete(Bundle bundle) {
        try {
            accessToken = Oauth2AccessToken.parseAccessToken(bundle);
            LogUtils.d(TAG,
                    "onComplete, accessToken is " + accessToken.getUid() + ":" + accessToken
                            .getToken() + ", expireTime is " + accessToken.getExpiresTime());
            if (accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(accessToken.getExpiresTime()));
                LogUtils.d(TAG, "weibo log in, expire date is " + date);
                afterLogin(VALUE_SINA, accessToken.getUid(), accessToken.getToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onWeiboException(WeiboException e) {
        LogUtils.d(TAG, "e.message is " + e.getLocalizedMessage());
        e.printStackTrace();
        Toast.makeText(getActivity(), String.format(getString(R.string.weibo_error), e.getMessage()),
                Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_CODE_BIND_OR_REGISTER
                || requestCode == REQUEST_CODE_COMPLETE_INFO) && resultCode == Activity.RESULT_OK) {
            getActivity().setResult(Activity.RESULT_OK);
            return;
        }
        // sso 授权回调
        try {
            if (mSsoHandler != null) {
                mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void afterLogin(int type, String uid, String token) {

    }

    protected void saveUserInfo(LoginResponse result) {
        Settings.saveUser(result.data);
        Global.currentUser = result.data;
    }
}
